package com.pilgrim.framework.common.util;

import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * MD5Util
 *
 * @author wangyibin
 * @version 1.0.0
 */
public class Md5Util {

    private static final String KEY_ALGORITHM_MD5 = "md5";
    private static final int RESULT_LENGTH = 32;
    private static final String CHARSET_UTF8 = "UTF-8";

    /**
     * 利用MD5进行加密
     *
     * @param plainText 待加密的字符串
     * @return 加密后的字符串
     */
    public static String encode(String plainText) {
        byte[] secretBytes;
        try {
            secretBytes = MessageDigest.getInstance(KEY_ALGORITHM_MD5).digest(plainText.getBytes(CHARSET_UTF8));
        } catch (Exception e) {
            throw new RuntimeException("没有md5这个算法！");
        }
        // 16进制数字
        String md5code = new BigInteger(1, secretBytes).toString(16);
        // 如果生成数字未满32位，需要前面补0
        if (md5code.length() < RESULT_LENGTH) {
            StringBuffer str0 = new StringBuffer();
            for (int i = 0; i < RESULT_LENGTH - md5code.length(); i++) {
                str0.append(0);
            }
            return str0.append(md5code).toString();
        } else {
            return md5code;
        }
    }
}
